const app = new getApp()
// const http = require("../config/api.js");

// 微信登录
function getLogin() {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        if (res.code) {
          console.log(res.code,111)
          wx.request({
            url: 'http://wechat.daoran.tv/API_UBP_TEST/wx/mp/userinfo5', 
            data: {
              code: res.code,
              project: 'lyhad',
              item: 65
            },
            method: 'post',
            header: {
              'content-type': 'application/json' // 默认值
            },
            success(res1) {
              wx.setStorageSync('openid',JSON.stringify(res1.data))
              console.log(res1,"用户信息")
              if (res1.data.memberId != '' && res1.data.memberId != undefined) {
                loginLinit(res1.data).then(res => {
                  wx.setStorageSync('isVIP', true)
                  resolve(res1.data)
                })
              } else {
                wx.setStorageSync('isVIP', false)
              }
            }
          })
        } else {
          wx.setStorageSync('isLogin', false)
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  })
}
/**
 *  获取用户是否是vip
 */
function loginLinit (data) {
  return new Promise((resolve, reject) => {
    wx.request({ // 获取用户是否是vip
      url: 'http://wechat.daoran.tv/API_UBP_TEST/user/login/init',
      data: {
        userId: data.openId,
        memberId: data.memberId,
        resolution: 1,
        platform: 2,
        stbType: 'wachat',
        province: '100',
        project: ['lyhad'],
        item: '65'
      },
      method: 'post',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.orderStatus == 0 || res.data.orderStatus == undefined || res.data.orderStatus == null) {
          wx.setStorageSync('isVIP', false)
          resolve(JSON.stringify(res.data))
        } else {
          wx.setStorageSync('isVIP', true)
          wx.setStorageSync('VIP', JSON.stringify(res.data))
          resolve(res)
        }
      }
    })
  })
  
} 
/**
 * 判断用户是否登录
 */
function checkLogin() {
  return new Promise(function (resolve, reject) {
    if (wx.getStorageSync('userInfo')) {
      checkSession().then(() => {
        resolve(true);
      }).catch(() => {
        reject(false);
      });
    } else {
      wx.setStorageSync('isVIP', false)
      reject(false);
    }
  });
}

/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        getLogin().then(res => {
          resolve(true)
        }).catch(res => {
          console.log('微信无法登陆，请检查网络')
        })
      }
    })
  });
}

// 用户授权
function getUser() {
  return new Promise((resolve, reject) => {
    wx.getUserInfo({
      success: function (res) {
        wx.setStorageSync('userInfo', JSON.stringify(res.userInfo))
        res.openId = JSON.parse(wx.getStorageSync('openid')).openId
        res.item = 65
        wx.request({
          url: 'http://wechat.daoran.tv/API_UBP_TEST/wx/minipro/memberInfo',
          data: res,
          method: 'post',
          header: {
            'content-type': 'application/json' // 默认值
          },
          success(res1) {
            console.log(res1)
            if (res1.data.code == '10000016') { // 后台无法获取seesion_key。所以要调用一次重新登录
              getLogin().then(res => {
                getUser().then(res => {})
              }).catch(res => {
                console.log('微信无法登陆，请检查网络')
              })
              return;
            }
            if (res1.data.memberId != '' && res1.data.memberId != undefined) {
              getApp().globalData.memberId = res1.data.memberId
              loginLinit(res1.data).then(res => {
                resolve(true)
              })
            } else {
              wx.setStorageSync('isVIP', false)
              reject(false)
            }
          }
        })
        // resolve(res)
      }
    })
  })
}

//生成UUID
function getUuid() {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4";
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid;
}

module.exports = {
  getLogin,
  getUser,
  checkLogin,
  checkSession,
  getUuid
}